package com.example.backend.controller;

import com.example.backend.domain.entity.SavedSearchCondition;
import com.example.backend.dto.*;
import com.example.backend.service.AdvancedSearchService;
import com.example.backend.service.StatisticsReportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 高级搜索和统计报表控制器
 */
@Tag(name = "高级搜索和统计报表", description = "工单高级搜索和统计报表功能接口")
@RestController
@RequestMapping("/api/search-reports")
public class SearchAndReportController {

    @Autowired
    private AdvancedSearchService advancedSearchService;

    @Autowired
    private StatisticsReportService statisticsReportService;

    // ==================== 高级搜索功能 ====================

    @Operation(summary = "执行高级搜索", description = "根据多条件执行工单高级搜索")
    @PostMapping("/advanced-search")
    public ResponseEntity<ApiResponse<AdvancedSearchResponse>> advancedSearch(
            @RequestBody AdvancedSearchRequest request) {
        try {
            AdvancedSearchResponse response = advancedSearchService.searchTickets(request);
            return ResponseEntity.ok(ApiResponse.success("高级搜索执行成功", response));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("高级搜索执行失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "保存搜索条件", description = "保存当前搜索条件供后续使用")
    @PostMapping("/save-search")
    public ResponseEntity<ApiResponse<SavedSearchCondition>> saveSearchCondition(
            @RequestBody AdvancedSearchRequest request,
            @Parameter(description = "用户ID") @RequestParam Long userId) {
        try {
            SavedSearchCondition savedSearch = advancedSearchService.saveSearchCondition(request, userId);
            return ResponseEntity.ok(ApiResponse.success("搜索条件保存成功", savedSearch));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("搜索条件保存失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取用户保存的搜索条件", description = "获取用户保存的所有搜索条件")
    @GetMapping("/saved-searches/{userId}")
    public ResponseEntity<ApiResponse<List<SavedSearchCondition>>> getUserSavedSearches(
            @Parameter(description = "用户ID") @PathVariable Long userId) {
        try {
            List<SavedSearchCondition> savedSearches = advancedSearchService.getUserSavedSearches(userId);
            return ResponseEntity.ok(ApiResponse.success("获取保存的搜索条件成功", savedSearches));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取保存的搜索条件失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取公开的搜索条件", description = "获取所有公开的搜索条件")
    @GetMapping("/public-searches")
    public ResponseEntity<ApiResponse<List<SavedSearchCondition>>> getPublicSavedSearches() {
        try {
            List<SavedSearchCondition> publicSearches = advancedSearchService.getPublicSavedSearches();
            return ResponseEntity.ok(ApiResponse.success("获取公开搜索条件成功", publicSearches));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取公开搜索条件失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "加载保存的搜索条件", description = "根据ID加载保存的搜索条件")
    @GetMapping("/load-search/{searchId}")
    public ResponseEntity<ApiResponse<AdvancedSearchRequest>> loadSavedSearch(
            @Parameter(description = "搜索条件ID") @PathVariable Long searchId) {
        try {
            AdvancedSearchRequest request = advancedSearchService.loadSavedSearch(searchId);
            return ResponseEntity.ok(ApiResponse.success("加载搜索条件成功", request));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("加载搜索条件失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "删除保存的搜索条件", description = "删除用户保存的搜索条件")
    @DeleteMapping("/delete-search/{searchId}")
    public ResponseEntity<ApiResponse<Void>> deleteSavedSearch(
            @Parameter(description = "搜索条件ID") @PathVariable Long searchId,
            @Parameter(description = "用户ID") @RequestParam Long userId) {
        try {
            advancedSearchService.deleteSavedSearch(searchId, userId);
            return ResponseEntity.ok(ApiResponse.success("删除搜索条件成功", null));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("删除搜索条件失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取搜索建议", description = "根据输入获取搜索建议")
    @GetMapping("/search-suggestions")
    public ResponseEntity<ApiResponse<List<String>>> getSearchSuggestions(
            @Parameter(description = "搜索关键词") @RequestParam String query,
            @Parameter(description = "用户ID") @RequestParam Long userId) {
        try {
            List<String> suggestions = advancedSearchService.getSearchSuggestions(query, userId);
            return ResponseEntity.ok(ApiResponse.success("获取搜索建议成功", suggestions));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取搜索建议失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取热门搜索", description = "获取热门搜索关键词")
    @GetMapping("/popular-searches")
    public ResponseEntity<ApiResponse<List<String>>> getPopularSearches() {
        try {
            List<String> popularSearches = advancedSearchService.getPopularSearches();
            return ResponseEntity.ok(ApiResponse.success("获取热门搜索成功", popularSearches));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取热门搜索失败: " + e.getMessage()));
        }
    }

    // ==================== 统计报表功能 ====================

    @Operation(summary = "获取实时统计仪表盘", description = "获取工单系统的实时统计数据")
    @GetMapping("/dashboard-stats")
    public ResponseEntity<ApiResponse<StatisticsReportDto.DashboardStats>> getDashboardStats() {
        try {
            StatisticsReportDto.DashboardStats stats = statisticsReportService.getDashboardStats();
            return ResponseEntity.ok(ApiResponse.success("获取仪表盘统计成功", stats));
        } catch (Exception e) {
            // 记录详细错误信息
            org.slf4j.LoggerFactory.getLogger(SearchAndReportController.class)
                .error("获取仪表盘统计失败", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("获取仪表盘统计失败: " + 
                    (e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName())));
        }
    }

    @Operation(summary = "获取团队绩效报表", description = "获取团队成员的绩效统计报表")
    @GetMapping("/team-performance")
    public ResponseEntity<ApiResponse<StatisticsReportDto.TeamPerformanceReport>> getTeamPerformanceReport() {
        try {
            StatisticsReportDto.TeamPerformanceReport report = statisticsReportService.getTeamPerformanceReport();
            return ResponseEntity.ok(ApiResponse.success("获取团队绩效报表成功", report));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取团队绩效报表失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取SLA统计报表", description = "获取SLA达成率统计报表")
    @GetMapping("/sla-statistics")
    public ResponseEntity<ApiResponse<StatisticsReportDto.SLAStatisticsReport>> getSLAStatisticsReport() {
        try {
            StatisticsReportDto.SLAStatisticsReport report = statisticsReportService.getSLAStatisticsReport();
            return ResponseEntity.ok(ApiResponse.success("获取SLA统计报表成功", report));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取SLA统计报表失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "获取趋势图表数据", description = "获取各种趋势图表的数据")
    @GetMapping("/trend-charts")
    public ResponseEntity<ApiResponse<StatisticsReportDto.TrendChartData>> getTrendChartData(
            @RequestParam(required = false) String timeRange,
            @RequestParam(required = false) String dimension) {
        try {
            StatisticsReportDto.TrendChartData chartData = statisticsReportService.getTrendChartData();
            return ResponseEntity.ok(ApiResponse.success("获取趋势图表数据成功", chartData));
        } catch (Exception e) {
            // 记录详细错误信息
            org.slf4j.LoggerFactory.getLogger(SearchAndReportController.class)
                .error("获取趋势图表数据失败", e);
            return ResponseEntity.badRequest()
                .body(ApiResponse.error("获取趋势图表数据失败: " + 
                    (e.getMessage() != null ? e.getMessage() : e.getClass().getSimpleName())));
        }
    }

    // ==================== 综合报表功能 ====================

    @Operation(summary = "获取综合统计报表", description = "获取包含所有统计信息的综合报表")
    @GetMapping("/comprehensive-report")
    public ResponseEntity<ApiResponse<StatisticsReportDto>> getComprehensiveReport() {
        try {
            StatisticsReportDto report = new StatisticsReportDto();
            
            report.setDashboardStats(statisticsReportService.getDashboardStats());
            report.setTeamPerformance(statisticsReportService.getTeamPerformanceReport());
            report.setSlaStatistics(statisticsReportService.getSLAStatisticsReport());
            report.setTrendCharts(statisticsReportService.getTrendChartData());
            
            return ResponseEntity.ok(ApiResponse.success("获取综合统计报表成功", report));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("获取综合统计报表失败: " + e.getMessage()));
        }
    }

    // ==================== 导出功能 ====================

    @Operation(summary = "导出搜索结果为Excel", description = "将搜索结果导出为Excel文件")
    @PostMapping("/export-search-results")
    public ResponseEntity<ApiResponse<String>> exportSearchResults(
            @RequestBody AdvancedSearchRequest request) {
        try {
            // 这里可以实现Excel导出功能
            String exportUrl = "/api/exports/search-results-" + System.currentTimeMillis() + ".xlsx";
            return ResponseEntity.ok(ApiResponse.success("导出搜索结果成功", exportUrl));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("导出搜索结果失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "导出统计报表为PDF", description = "将统计报表导出为PDF文件")
    @GetMapping("/export-report-pdf")
    public ResponseEntity<ApiResponse<String>> exportReportPdf(
            @Parameter(description = "报表类型") @RequestParam String reportType) {
        try {
            // 这里可以实现PDF导出功能
            String exportUrl = "/api/exports/report-" + reportType + "-" + System.currentTimeMillis() + ".pdf";
            return ResponseEntity.ok(ApiResponse.success("导出统计报表成功", exportUrl));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("导出统计报表失败: " + e.getMessage()));
        }
    }

    // ==================== 缓存管理 ====================

    @Operation(summary = "清除统计缓存", description = "清除统计数据的缓存")
    @PostMapping("/clear-cache")
    public ResponseEntity<ApiResponse<Void>> clearStatisticsCache() {
        try {
            // 这里可以实现缓存清除功能
            return ResponseEntity.ok(ApiResponse.success("清除缓存成功", null));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("清除缓存失败: " + e.getMessage()));
        }
    }

    @Operation(summary = "刷新统计数据", description = "强制刷新所有统计数据")
    @PostMapping("/refresh-statistics")
    public ResponseEntity<ApiResponse<Void>> refreshStatistics() {
        try {
            // 这里可以实现统计数据刷新功能
            return ResponseEntity.ok(ApiResponse.success("刷新统计数据成功", null));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.error("刷新统计数据失败: " + e.getMessage()));
        }
    }
}
